package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间段内营业额
     * @param begin 开始日期
     * @param end 结束日期
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        log.info("开始统计营业额，开始日期：{}，结束日期：{}", begin, end);
        //存放从开始日期到结束日期的每一天
        List<LocalDate> list = getLocalList(begin, end);
        //将dateList转换成字符串，以逗号分隔
        String dateList = StringUtils.join(list, ",");

        //存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();

        //查询营业额
        for (LocalDate date : list){
            //查询对应的日期 状态为已完成的订单
            //开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //select sum(amount) from order where order_date > ? and status = 5 and order_date < ?
            //order_date > ? 表示查询大于开始日期的订单
            //order_date < ? 表示查询小于结束日期的订单
            //status = 5 表示查询状态为已完成的订单
            //amount 表示订单的总金额
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            //如果turnover为null，则默认为0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //封装返回值
        return TurnoverReportVO
                .builder()
                .dateList(dateList)
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 统计指定时间段内用户数量
     * @param begin 开始日期
     * @param end 结束日期
     */

    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        log.info("开始统计用户，开始日期：{}，结束日期：{}", begin, end);
        //存放从开始日期到结束日期的每一天
        List<LocalDate> list = getLocalList(begin, end);
        //将dateList转换成字符串，以逗号分隔
        String dateList = StringUtils.join(list, ",");

        //存放每天的新增用户数量select count(id) from user where create_time > ? and create_time < ?
        List<Integer> newUserList = new ArrayList<>();
        //存放每天的总用户数量select count(id) from user where create_time < ?
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : list){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end", endTime);
            Integer  totalUser = userMapper.contByMap(map);
            //如果totalUser为null，则默认为0
            totalUser = totalUser == null ? 0 : totalUser;
            map.put("begin", beginTime);
            Integer newUser = userMapper.contByMap(map);
            //如果newUser为null，则默认为0
            newUser = newUser == null ? 0 : newUser;
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        //封装返回值
        return UserReportVO.builder()
                .dateList(dateList)
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        log.info("开始统计订单，开始日期：{}，结束日期：{}", begin, end);

        //存放从开始日期到结束日期的每一天
        List<LocalDate> list = getLocalList(begin, end);
        //将dateList转换成字符串，以逗号分隔
        String dateList = StringUtils.join(list, ",");

        //存放每天的订单总数
        List<Integer> orderCountList = new ArrayList<>();

        //每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : list){
            //查询每天的订单总数
            //select count(id) from order where order_date > ? and order_date < ?
            //order_date > ? 表示查询大于开始日期的订单
            //order_date < ? 表示查询小于结束日期的订单
            //count(id) 表示订单的总数
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //查询有效订单数
            //select count(id) from order where order_date > ? and order_date < ? and status = 5
            //status = 5 表示查询状态为已完成的订单
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            //订单总数
            orderCountList.add(orderCount);
            //有效订单数
            validOrderCountList.add(validOrderCount);
        }
        //计算时间区间内的订单总数
        Integer totalOrdetCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单
        Integer totalValidOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrdetCount != 0){
            orderCompletionRate = totalValidOrderCount.doubleValue() / totalOrdetCount;
        }
        //封装返回值
        return OrderReportVO
                .builder()
                .dateList(dateList)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrdetCount)
                .validOrderCount(totalValidOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 统计指定日期销售前10的商品
     * @param begin
     * @param end
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        //stream流操作
        List<String> names = salesTop10.stream()
                .map(GoodsSalesDTO::getName)
                .collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop10.stream()
                .map(GoodsSalesDTO::getNumber)
                .collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");
        //封装返回值
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出营业数据报表
     * @param response
     */
    @Override
    public void exportbusinessData(HttpServletResponse response) {
        //查询数据库获取营业数据
        //
        LocalDate dateBegin = LocalDate.now().minusDays(30);

        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dateEnd, LocalTime.MAX);
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);

        //通过POI将数据写入到excel中
        //this.getClass().getClassLoader()：获取当前类的类加载器。
        //getResourceAsStream("template/运营数据报表模板.xlsx")：
        // 通过类加载器获取指定路径下的资源文件，
        // 并返回一个InputStream对象，用于读取该文件的内容。
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //填充数据
            XSSFSheet sheet1 = excel.getSheet("sheet1");


            sheet1.getRow(1).getCell(1).setCellValue("时间："+dateBegin + "至" + dateEnd);
            //获取第4行
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取第5行
            row =  sheet1.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());

            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }


            //通过输出流将excel下载到浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭流
            out.close();
            in.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据条件查询订单总数
     * @param begin
     * @param end
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 获取从开始日期到结束日期的每一天
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getLocalList(LocalDate begin, LocalDate end) {
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        //begin.isBefore(end)
        while (!begin.equals(end)){
            //begin.plusDays(1)表示下一天
            begin = begin.plusDays(1);
            list.add(begin);
        }
        return list;
    }

}
